package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.wmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

   @Autowired
   private wmNewsTaskService taskService;

    /**
     * 根据条件查询文章的分页数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findPage(WmNewsPageReqDto dto) {
        //1. 校验参数
        if(null == dto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();

        //2. 构建查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        if(null != dto.getChannelId()){
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if(null != dto.getBeginPubDate() && null != dto.getEndPubDate()){
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        if(null != dto.getStatus()){
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        if(null != dto.getKeyword()){
            queryWrapper.like(WmNews::getTitle, "%" + dto.getKeyword() + "%");
        }

        //3. 构建分页参数
        IPage<WmNews> page = new Page(dto.getPage(), dto.getSize());

        //4. 查询
        page = page(page, queryWrapper);

        //5. 封装返回结果进行数据返回
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int)page.getTotal());

        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //1. 数据的校验
        if(dto == null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 保存或者更新文章的数据
        WmNews wmNews = saveOrUpdateNews(dto);

        //3. 判断文章提交的时候是直接提交还是保存草稿-如果是保存草稿则直接反馈
        if(dto.getStatus() == 0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //4. 从内容中抽取所有的图片
        List<String> imageUrls = ectractUrlInfo(dto.getContent());

        //5. 批量保存内容中的图片和素材之间的关系
        saveRelativeInfoForContent(imageUrls, wmNews.getId());

        //6. 保存封面图片和素材之间的关系-封面如果是自动需要自己按照规则匹配图片然后再保存数据关系
        saveRelativeInfoForCover(dto.getImages(), imageUrls, wmNews, dto.getType());

        //7. 审核文章-添加审核任务到schedule服务
//        autoScanService.autoScanWmNews(wmNews.getId());

        taskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片和素材之间的关系  文章封面类型  0 无图 1 单图 3 多图 -1 自动
     * @param images
     * @param imageUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(List<String> images, List<String> imageUrls, WmNews wmNews, Short type) {

        if(type == -1){
            if(null ==imageUrls || imageUrls.size() == 0){
                //设置文章的类型位无图
                wmNews.setType((short)0);
            }else if(imageUrls.size() < 3){
                //抽取一个图片作为封面
                images.add(imageUrls.get(0));
                wmNews.setType((short)1);
            }else{
                images.addAll(imageUrls.stream().limit(3).collect(Collectors.toList()));
                wmNews.setType((short)3);
            }

            //更新文章-更新文章的类型
            updateById(wmNews);
        }

        if(null != images && images.size() > 0){
            saveRelativeInfo(images, wmNews.getId(), (byte) 1);
        }
    }


    private void saveRelativeInfo(List<String> imageUrls, Integer wmNesId, byte type){
        //数据校验
        if(null == imageUrls || imageUrls.size() == 0){
            return;
        }

        //图片集合里面可能存在相同的图片需要去重
        imageUrls = imageUrls.stream().distinct().collect(Collectors.toList());

        // 通过图片的地址查询图片的id
        List<WmMaterial> list = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageUrls));

        //判断数据是否被删除过了
        if(null == list || list.size() != imageUrls.size()){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //通过素材的到素材的id
        /*List<Integer> materialIds  = new ArrayList<>();
        for (WmMaterial wmMaterial : list) {
            materialIds.add(wmMaterial.getId());
        }*/
        List<Integer> materialIds = list.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());

        wmNewsMaterialMapper.batchInsert(materialIds, wmNesId, type);
    }

    private void saveRelativeInfoForContent(List<String> imageUrls, Integer id) {
        saveRelativeInfo(imageUrls, id, (byte) 0);
    }


    /**
     * 抽取文章内容里面的所有的图片
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);

        List<String> result = new ArrayList<>();

        if(null != list && list.size() > 0){
            for (Map map : list) {
                if("image".equals(map.get("type"))){
                    result.add(map.get("value").toString());
                }
            }
        }

        return result;

    }

    /**
     * 保存或者更新文章数据
     * @param dto
     * @return
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();

        /**
         * 把dto中数据拷贝到wmNews对象
         *    1. 2个对象的属性名称必须要一样
         *    2. 2个对象的属性的类型必须要一样
         */
        BeanUtils.copyProperties(dto, wmNews);

        //封面图片数据拷贝不会成功需要我们自己处理-List ->string
        if(null != dto.getImages() && dto.getImages().size() > 0){
            String images = StringUtils.join(dto.getImages().toArray(), ",");
            wmNews.setImages(images);
        }

        //如果类型是无图数据无法存储到数据库需要把数据设置位 null
        if(dto.getType() == -1){
            wmNews.setType(null);
        }

        //判断dto中是否有id 如果有则执行更新 如果没有则执行新增
        if(null == dto.getId()){
            //新增
            save(wmNews);
        }else {
            //删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));

            //更新
            updateById(wmNews);
        }

        return wmNews;
    }
}
